package com.hxd.otc.module.order.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.event.Event;
import com.hxd.otc.module.my.activity.ChatActivity;
import com.hxd.otc.module.order.adapter.OrderDetailBankAdapter;
import com.hxd.otc.module.order.bean.AllOrderBean;
import com.hxd.otc.module.order.bean.BankInfoPoData;
import com.hxd.otc.module.order.contract.BuyOrderDetailContract;
import com.hxd.otc.module.order.fragment.AllOrderFragment;
import com.hxd.otc.module.order.fragment.ConfirmPaymentDialogFragment;
import com.hxd.otc.module.order.presenter.BuyOrderDetailPresenter;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.CountDownUtils;
import com.hxd.otc.utils.DateUtil;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 作  者 :  zjl
 * 时  间 :  2018/6/5 17:19
 * 描  述 :  ${}买入 订单详情页
 */
public class BuyOrderDetailActivity extends PermissionActivity<BuyOrderDetailPresenter> implements BuyOrderDetailContract.View {

    @BindView(R.id.bt_right1)
    TextView btRight1;

    @BindView(R.id.bt_right2)
    TextView btRight2;

    @BindView(R.id.tv_red)
    TextView tvRed;

    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.tv_name)
    TextView tvName;

    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;

    @BindView(R.id.tv_account)
    TextView tvAccount;

    @BindView(R.id.tv_account_unit)
    TextView tvAccountUnit;

    @BindView(R.id.tv_pay_state)
    TextView tvPayState;

    @BindView(R.id.tv_time)
    TextView tvTime;

    @BindView(R.id.tv_price)
    TextView tvPrice;

    @BindView(R.id.tv_number)
    TextView tvNumber;

    @BindView(R.id.iv_sliver)
    ImageView ivSliver;

    @BindView(R.id.ll_pay_infom)
    LinearLayout llPayInfom;

    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;

    @BindView(R.id.ll_all)
    LinearLayout llAll;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.rc_bank)
    RecyclerView rcBank;

    @BindView(R.id.iv_tag)
    ImageView ivTag;

    @BindView(R.id.tv_other_name)
    TextView tvOtherName;
    /**
     * 订单 买入 状态
     * //0:买入下单|卖出下单;1:确认付款了,9:取消,2:确认收到款,3:确认没收到款
     */
    public static final int BUY_UNPAID = 0;//未付款
    public static final int BUY_PAYED = 1;//已付款
    public static final int BUY_REPRESENTATION = 3;//申诉中
    public static final int BUY_CANCLED = 9;//已取消
    public static final int BUY_FINISHED = 2;//已完成

    public static final int SALE_PAYED_REQUEST = 123;//申诉 requestCode

    public static final int CANCLE_DETAL_SUCCESS = 1;//取消订单操作成功
    public static final int PAYIING_SUCCESS = 3;// 我已付款 操作成功
    public static final int WITHDRAW_SUCCESS = 5;// 撤回申诉 操作成功

    AllOrderBean.DataBean orderBean;

    MultipleBlocksDialog cancleDealDailog;
    MultipleBlocksDialog callDailog;

    OrderDetailBankAdapter bankAdapter;

    Disposable mDisposable;

    boolean isRefresh;//是否通知去刷新 订单列表的数据
    int statue = -1;//记录订单状态是否改变
    boolean isFrist = true;//
    boolean isRefreshRedMess;//刷新融云消息
    private ConfirmPaymentDialogFragment mPaymentDialogFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_buy_order_detail;
    }

    @Override
    protected void initView() {
        orderBean = (AllOrderBean.DataBean) getIntent().getExtras().getSerializable(AllOrderFragment.ORDERINFO);

//        refreshData();

        rcBank.setLayoutManager(new LinearLayoutManager(this));
        bankAdapter = new OrderDetailBankAdapter();
        rcBank.setAdapter(bankAdapter);
        rcBank.setNestedScrollingEnabled(false);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadData(orderBean.subOrderId);
            }
        });

        bankAdapter.setLinenster(new OrderDetailBankAdapter.OnItemClickLinenster() {
            @Override
            public void clickName(BankInfoPoData item) {
                if (item.type == 3) {
                    copyData(item.realName);
                }
            }

            @Override
            public void clickNumber(BankInfoPoData item) {
                if (item.type == 3) {
                    copyData(item.payNo);
                }
            }

            @Override
            public void clickItem(BankInfoPoData item) {
                if (item.type != 3) {
                    Bundle bundle = new Bundle();
                    bundle.putString("alipayAddress", item.qrcodeId);
                    bundle.putInt("type", item.type);
                    $startActivity(AlipayQRcodeActivity.class, bundle);
                }
            }
        });


    }

    @Override
    protected void initData() {
        if (getIntent().getExtras().containsKey(OrderFinishedActivity.ISREFRESH_ORDER_LIST_DATA)) {
            isRefresh = getIntent().getExtras().getBoolean(OrderFinishedActivity.ISREFRESH_ORDER_LIST_DATA);
        }
        refreshLayout.autoRefresh(0, 10, 1);
        mPresenter.getOrderBankList(orderBean.subOrderId);
    }

    @Override
    public void onSetData(AllOrderBean.DataBean bean) {

        orderBean = bean;
        if (isFrist) {
            statue = orderBean.status;
            isFrist = false;
        }
        refreshData();

    }

    @Override
    public void refreshView(int type) {
        setResult(RESULT_OK);
        dismissSpinnerDlg();
        switch (type) {
            case CANCLE_DETAL_SUCCESS:
                orderBean.status = 9;
                refreshData();
                break;
            case PAYIING_SUCCESS:
                orderBean.status = 1;
                refreshData();
                break;
            case WITHDRAW_SUCCESS:
                orderBean.status = 3;
                refreshData();
                break;
        }
    }

    @Override
    public void getBankList(List<BankInfoPoData> bankInfoPoData) {

        bankAdapter.setNewData(bankInfoPoData);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isRefreshRedMess) {
            getRongUnreadCount();
            isRefreshRedMess = false;
        }
    }

    @Override
    public void onHideLoading() {
        super.onHideLoading();
        refreshLayout.finishRefresh();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected BuyOrderDetailPresenter createPresenter() {
        return new BuyOrderDetailPresenter(this);
    }

    private void refreshData() {
        llAll.setVisibility(View.VISIBLE);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        titleBar.setTitleText(getString(R.string.order_detail_buy_aec, orderBean.symbol));
        tvName.setText(orderBean.getAskNickName());
        tvOrderNumber.setText("#" + orderBean.subOrderId);
        tvAccount.setText(StringUtil.format8Number(orderBean.totalPrice));
        tvAccountUnit.setText(orderBean.supportCurrencyCode);

        tvNumber.setText(getResources().getString(R.string.number_detail,
                StringUtil.format8Number(orderBean.volume), orderBean.symbol));
        tvPrice.setText(getResources().getString(R.string.price_detail,
                orderBean.price + "",
                orderBean.supportCurrencyCode + "/" + orderBean.symbol));

        if (orderBean.askUserId.equals(orderBean.orderUserId)) {
            ivSliver.setVisibility(View.VISIBLE);
        } else {
            ivSliver.setVisibility(View.GONE);
        }

        //处理付款人信息
        String confirmPaymentName = StringUtil.emptyIfNull(orderBean.getConfirmPaymentName()).trim();
        if (TextUtils.isEmpty(confirmPaymentName)) {
            tvOtherName.setVisibility(View.GONE);
        } else {
            tvOtherName.setVisibility(View.VISIBLE);
            tvOtherName.setText(ResourceUtil.getString(R.string.order_pay_account_info, confirmPaymentName));
        }

        switch (orderBean.status) {
            case BUY_UNPAID:
                llBottom.setVisibility(View.VISIBLE);
                ivTag.setVisibility(View.GONE);

                tvPayState.setTextColor(getResources().getColor(R.color.color_FFFF7766));
                tvPayState.setText(getResources().getString(R.string.order_un_pay));

                btRight1.setVisibility(View.VISIBLE);
                btRight1.setBackgroundColor(getResources().getColor(R.color.color_FF5AC792));
                btRight1.setTextColor(getResources().getColor(R.color.colorWhite));
                btRight1.setText(getString(R.string.payed));

                btRight2.setVisibility(View.VISIBLE);
                btRight2.setText(getString(R.string.deal_cancle_order));
                btRight2.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                btRight2.setTextColor(getResources().getColor(R.color.color_FF464E5F));

                ivSliver.setImageResource(R.mipmap.order_trading_v_icon);
                tvAccount.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                tvAccountUnit.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                tvName.setTextColor(getResources().getColor(R.color.color_FF464E5F));

                tvTime.setTextColor(getResources().getColor(R.color.color_FFFF7766));
                if (orderBean.remainingTime > 0) {
                    tvTime.setVisibility(View.VISIBLE);
                    interval(Integer.parseInt(orderBean.remainingTime + ""));
                }
                break;
            case BUY_PAYED:
                llBottom.setVisibility(View.VISIBLE);
                ivTag.setVisibility(View.GONE);
                tvTime.setVisibility(View.GONE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FF5AC792));
                tvPayState.setText(getResources().getString(R.string.order_pay));
                btRight2.setVisibility(View.GONE);

                btRight1.setVisibility(View.VISIBLE);
                btRight1.setText(getString(R.string.representation));
                btRight1.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                btRight1.setTextColor(getResources().getColor(R.color.color_FF464E5F));

                ivSliver.setImageResource(R.mipmap.order_trading_v_icon);
                tvAccount.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                tvAccountUnit.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                tvName.setTextColor(getResources().getColor(R.color.color_FF464E5F));
                break;
            case BUY_REPRESENTATION:
                ivTag.setVisibility(View.GONE);
                btRight1.setVisibility(View.GONE);
                tvTime.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FFFF7766));
                btRight2.setVisibility(View.GONE);

                break;
            case BUY_CANCLED:
                tvPayState.setTextColor(getResources().getColor(R.color.color_FF95A2AC));
                tvPayState.setText(getResources().getString(R.string.order_cancle));
                ivTag.setVisibility(View.VISIBLE);
                llPayInfom.setVisibility(View.GONE);
                llBottom.setVisibility(View.GONE);
                tvTime.setVisibility(View.GONE);
                tvAccount.setTextColor(getResources().getColor(R.color.color_FF95A2AC));
                tvAccountUnit.setTextColor(getResources().getColor(R.color.color_FF95A2AC));
                tvName.setTextColor(getResources().getColor(R.color.color_FF95A2AC));
                ivSliver.setImageResource(R.mipmap.order_cancle_trading_v_icon);
                break;
            case BUY_FINISHED:
                $setResult();
                if (orderBean != null && (orderBean.status == 0 || orderBean.status == 1))//订单状态发生改变时 通知更新红点
                    postSticky(new Event.RefreshOrderRedEvent(statue, true));
                Bundle bundle = new Bundle();
                bundle.putSerializable(AllOrderFragment.ORDERINFO, orderBean);
                bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, true);
                $startActivity(OrderFinishedActivity.class, bundle, true);
                break;
        }
    }


    /**
     * 未付款和 已付 倒计时款操作
     */
    public void interval(int count) {
        CountDownUtils.interval(count, new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
            }

            @Override
            public void onNext(Long along) {
                tvTime.setText(DateUtil.getTimeMinutesSecond(along));
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                //当倒计时完成，则需要请求订单详情接口，刷新数据，取消订单
                mPresenter.doLoadData(orderBean.subOrderId);
            }
        });
    }

    @Override
    protected void initPermissions() {
        super.initPermissions();
    }

    @OnClick({R.id.rl_contact, R.id.bt_call, R.id.bt_right2, R.id.bt_right1, R.id.back_tv, R.id.tv_order_number})
    public void onCliekEvent(View view) {
        switch (view.getId()) {
            case R.id.back_tv: //关闭当页面要发送给订单列表去更新数据
                if (orderBean != null && isRefresh)
                    postSticky(new Event.RefreshOrderListEvent(orderBean.status, true));
                finish();
                break;
            case R.id.rl_contact: //联系对方
                isRefreshRedMess = true;
                Bundle bundle = new Bundle();
                bundle.putSerializable(ChatActivity.EXTRA_ORDER_INFO, orderBean);
                RongIM.getInstance().startConversation(this, Conversation.ConversationType.PRIVATE,
                        orderBean.getAskUserId(), orderBean.getAskNickName(), bundle);
                break;
            case R.id.bt_call://打电话
                call();
                break;
            case R.id.bt_right2:// 最右边按钮 的 左边按钮
                btRight2Click();
                break;
            case R.id.bt_right1:// z最右边的按钮
                btRight1Click();
                break;
            case R.id.tv_order_number:// z最右边的按钮
                copyData(orderBean.subOrderId);
                break;
        }
    }

    private void btRight1Click() {
        switch ((orderBean.status)) {
            case BUY_UNPAID://未付款 ：我已付款  按钮
                payingClick();
                break;
            case BUY_PAYED://已付款 ----申诉按钮
                Bundle bundle = new Bundle();
                bundle.putString(AllOrderFragment.ORDER_ID, orderBean.subOrderId);
                $startActivityForResult(ComplainActivity.class, bundle, SALE_PAYED_REQUEST);
                break;
            case BUY_REPRESENTATION://申诉中---没有状态
                break;
        }
    }

    /**
     * 获取融云未读消息数
     */
    private void getRongUnreadCount() {
        RongIMClient.getInstance().getUnreadCount(Conversation.ConversationType.PRIVATE, orderBean.subOrderId, new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                if (integer != null && integer > 0) {
                    tvRed.setVisibility(View.VISIBLE);
                    tvRed.setText(String.valueOf(integer));
                } else {
                    tvRed.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
            }
        });
    }

    private void btRight2Click() {
        switch (orderBean.status) {
            case BUY_UNPAID://未付款 ：  //点击取消订单，则还是代付款状态，但是按钮变成 已提交取消
                cancleDealClick(getString(R.string.deal_cancle_order));
                break;
            case BUY_PAYED://已付款 状态---取消交易 按钮
                cancleDealClick(getString(R.string.deal_cancle));
                break;
            case BUY_REPRESENTATION://申诉中----是撤回申诉状态，还是联系客服状态（接入美洽客户就好了）
                break;
        }
    }

    private void copyData(String bankNo) {
        CommonUtil.copyData(bankNo);
        BlocksToast.get().showToast(UIUtils.getContext().getString(R.string.copy_number_hint));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SALE_PAYED_REQUEST && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
//            mPresenter.doLoadData(orderBean.id);
        }
    }

    private void call() {
        if (callDailog == null) {
            callDailog = new MultipleBlocksDialog(this)
                    .setContent(orderBean.askUserMobile)
                    .setTitle(orderBean.getAskNickName())
                    .setTvCancle(getString(R.string.cancel))
                    .setTvSure(getString(R.string.dial), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CommonUtil.callPhone(BuyOrderDetailActivity.this, orderBean.askUserMobile);
                            callDailog.dismiss();
                        }
                    });
        }
        callDailog.show();
    }

    /**
     * 取消付款操作操作
     */
    private void cancleDealClick(String str) {
        if (cancleDealDailog == null)
            cancleDealDailog = new MultipleBlocksDialog(this)
                    .setContent(Html.fromHtml(getString(R.string.buy_order_deal_cancel_hint)))
                    .setTitle(str)
                    .setCbText(getString(R.string.cb_confirm_no_pay))
                    .setTvCancle(getString(R.string.let_me_think))
                    .setTvSure(getString(R.string.confirm_cancel), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (cancleDealDailog.getmAgreeCheck().isChecked()) {
                                cancleDealDailog.dismiss();
                                showSpinnerDlg("", true);
                                mPresenter.cancleDetal(orderBean.subOrderId, orderBean.isNosenseOrder() ? "1" : "0");
                            } else {
                                BlocksToast.get().showToast(getString(R.string.please_check_the_agreement));
                            }
                        }
                    });
        cancleDealDailog.show();
    }

    /**
     * 我已付款操作----点击我已付款，然后需要对方确认收款，这边才能操作
     */
    private void payingClick() {
        if (mPaymentDialogFragment == null) {
            mPaymentDialogFragment = ConfirmPaymentDialogFragment.getInstance()
                    .setOnPayAccountInfoListener(new ConfirmPaymentDialogFragment.OnPayAccountInfoListener() {
                        @Override
                        public void onPayAccountInfo(String confirmPaymentName, String supportPay) {
                            showSpinnerDlg("", true);
                            mPresenter.paying(orderBean.subOrderId, confirmPaymentName, supportPay, orderBean.isNosenseOrder() ? "1" : "0");
                        }
                    });
        }
        if (!mPaymentDialogFragment.isAdded()
                && !mPaymentDialogFragment.isVisible()
                && !mPaymentDialogFragment.isRemoving()) {
            mPaymentDialogFragment.show(getSupportFragmentManager(), ConfirmPaymentDialogFragment.class.getSimpleName());
        }
    }

    /**
     * 付款成功
     *
     * @param confirmPaymentName 付款账号信息
     */
    @Override
    public void paidOrderSuccess(String confirmPaymentName) {
        orderBean.setConfirmPaymentName(confirmPaymentName);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (orderBean != null && isRefresh)
                postSticky(new Event.RefreshOrderListEvent(orderBean.status, true));
        }
        return super.onKeyDown(keyCode, event);


    }

    @Override
    public void onError(int code) {
        super.onError(code);
        refreshLayout.finishRefresh();
        dismissSpinnerDlg();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(cancleDealDailog);
        UIUtils.dismissDialog(callDailog);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

}
